<!--
 * @FilePath: /web-vue/src/views/House/index.vue
 * @Description: 【房源】管理主页
-->
<template>
  <div>
    <el-row class="data-table row-panel row-panel-first">
      <el-col>
        <el-card>
          <el-row :gutter="0">
            <!-- 【房源】参数 -->
            <el-col>
              <el-form :model="queryForm" size="medium" :inline="true">
                <table
                  style="border-collapse: collapse; width: 100%"
                  class="table-common-style"
                >
                  <colgroup>
                    <col width="11.11%" />
                    <col width="11.11%" />
                    <col width="11.11%" />
                    <col width="11.11%" />
                    <col width="11.11%" />
                    <col width="11.11%" />
                    <col width="11.11%" />
                    <col width="11.11%" />
                    <col width="11.11%" />
                  </colgroup>
                  <tbody>
                    <tr>
                      <td><div class="form-item-label">ID：</div></td>
                      <td colspan="2">
                        <el-form-item valign="middle" prop="id">
                          <el-input
                            v-model.trim="queryForm.id"
                            placeholder="请输入查询参数"
                            clearable
                          >
                          </el-input>
                        </el-form-item>
                      </td>
                      <td><div class="form-item-label">房间标题：</div></td>
                      <td colspan="2">
                        <el-form-item valign="middle" prop="houseTitle">
                          <el-input
                            v-model.trim="queryForm.houseTitle"
                            placeholder="请输入查询参数"
                            clearable
                          >
                          </el-input>
                        </el-form-item>
                      </td>
                      <td><div class="form-item-label">地区：</div></td>
                      <td colspan="2">
                        <el-form-item valign="middle" prop="regionId">
                          <el-input
                            v-model.trim="queryForm.regionId"
                            placeholder="请输入查询参数"
                            clearable
                          >
                          </el-input>
                        </el-form-item>
                      </td>
                    </tr>
                    <tr>
                      <td><div class="form-item-label">具体位置：</div></td>
                      <td colspan="2">
                        <el-form-item valign="middle" prop="detailLocation">
                          <el-input
                            v-model.trim="queryForm.detailLocation"
                            placeholder="请输入查询参数"
                            clearable
                          >
                          </el-input>
                        </el-form-item>
                      </td>
                      <td><div class="form-item-label">房源类型：</div></td>
                      <td colspan="2">
                        <el-form-item valign="middle" prop="houseType">
                          <el-select
                            v-model="queryForm.houseType"
                            filterable
                            clearable
                            placeholder="请选择查询参数"
                            @change="queryDataBtn()"
                          >
                            <el-option
                              v-for="item in $store.state.DICT.houseTypeSelect"
                              :key="item.code"
                              :label="item.name"
                              :value="item.code"
                            >
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </td>
                      <td><div class="form-item-label">配套服务设施：</div></td>
                      <td colspan="2">
                        <el-form-item valign="middle" prop="provide">
                          <el-input
                            v-model.trim="queryForm.provide"
                            placeholder="请输入查询参数"
                            clearable
                          >
                          </el-input>
                        </el-form-item>
                      </td>
                    </tr>
                    <tr>
                      <td><div class="form-item-label">入住要求：</div></td>
                      <td colspan="2">
                        <el-form-item valign="middle" prop="command">
                          <el-input
                            v-model.trim="queryForm.command"
                            placeholder="请输入查询参数"
                            clearable
                          >
                          </el-input>
                        </el-form-item>
                      </td>
                      <td><div class="form-item-label">房源状态：</div></td>
                      <td colspan="2">
                        <el-form-item valign="middle" prop="houseStatus">
                          <el-select
                            v-model="queryForm.houseStatus"
                            filterable
                            clearable
                            placeholder="请选择查询参数"
                            @change="queryDataBtn()"
                          >
                            <el-option
                              v-for="item in $store.state.DICT
                                .houseStatusSelect"
                              :key="item.code"
                              :label="item.name"
                              :value="item.code"
                            >
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </td>
                      <td><div class="form-item-label">组织机构：</div></td>
                      <td colspan="2">
                        <el-form-item valign="middle" prop="organizationId">
                          <el-input
                            v-model.trim="queryForm.organizationId"
                            placeholder="请输入查询参数"
                            clearable
                          >
                          </el-input>
                        </el-form-item>
                      </td>
                    </tr>
                    <tr>
                      <td><div class="form-item-label">创建人：</div></td>
                      <td colspan="2">
                        <el-form-item valign="middle" prop="createUser">
                          <el-input
                            v-model.trim="queryForm.createUser"
                            placeholder="请输入查询参数"
                            clearable
                          >
                          </el-input>
                        </el-form-item>
                      </td>
                      <td><div class="form-item-label">创建人姓名：</div></td>
                      <td colspan="2">
                        <el-form-item valign="middle" prop="createUserName">
                          <el-input
                            v-model.trim="queryForm.createUserName"
                            placeholder="请输入查询参数"
                            clearable
                          >
                          </el-input>
                        </el-form-item>
                      </td>
                      <td><div class="form-item-label">创建时间：</div></td>
                      <td colspan="2">
                        <el-form-item valign="middle" prop="createTime">
                          <el-date-picker
                            v-model="queryForm.createTime"
                            :picker-options="DateRange_Picker_Option"
                            type="daterange"
                            align="right"
                            unlink-panels
                            range-separator="——"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            value-format="yyyy/MM/dd"
                          >
                          </el-date-picker>
                        </el-form-item>
                      </td>
                    </tr>
                    <tr>
                      <td><div class="form-item-label">更新人：</div></td>
                      <td colspan="2">
                        <el-form-item valign="middle" prop="updateUser">
                          <el-input
                            v-model.trim="queryForm.updateUser"
                            placeholder="请输入查询参数"
                            clearable
                          >
                          </el-input>
                        </el-form-item>
                      </td>
                      <td><div class="form-item-label">更新人姓名：</div></td>
                      <td colspan="2">
                        <el-form-item valign="middle" prop="updateUserName">
                          <el-input
                            v-model.trim="queryForm.updateUserName"
                            placeholder="请输入查询参数"
                            clearable
                          >
                          </el-input>
                        </el-form-item>
                      </td>
                      <td><div class="form-item-label">更新时间：</div></td>
                      <td colspan="2">
                        <el-form-item valign="middle" prop="updateTime">
                          <el-date-picker
                            v-model="queryForm.updateTime"
                            :picker-options="DateRange_Picker_Option"
                            type="daterange"
                            align="right"
                            unlink-panels
                            range-separator="——"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            value-format="yyyy/MM/dd"
                          >
                          </el-date-picker>
                        </el-form-item>
                      </td>
                    </tr>
                    <tr>
                      <td colspan="10">
                        <!-- 按钮 -->
                        <el-form-item>
                          <el-button
                            type="primary"
                            icon="el-icon-search"
                            @click="queryDataBtn()"
                            :loading="requestLoading"
                            >查询
                          </el-button>
                          <el-button
                            type="success"
                            icon="el-icon-document-add"
                            @click="$refs.addForm.openAddForm(true)"
                            >新增
                          </el-button>
                          <el-button
                            type="danger"
                            icon="el-icon-delete"
                            @click="batchDelHouseApi()"
                            >删除
                          </el-button>
                          <el-button
                            v-if="$store.state.auth.isAudit"
                            type="warning"
                            icon="el-icon-thumb"
                            @click="authSysRoleDatascope()"
                            >批量审批
                          </el-button>
                          <el-button
                            icon="el-icon-refresh-left"
                            @click="
                              () =>
                                Object.assign(
                                  this.queryForm,
                                  this.$options.data().queryForm
                                )
                            "
                            >清空查询条件
                          </el-button>
                        </el-form-item>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </el-form>
            </el-col>
            <!-- 【房源】信息表 -->
            <el-col>
              <el-divider content-position="left">
                <h3>房源信息表</h3>
              </el-divider>
              <el-table
                :data="tableData"
                row-key="id"
                max-height="400"
                border
                highlight-current-row
                v-loading="requestLoading"
                element-loading-text="正在拼命加载，请耐心等待！"
                element-loading-spinner="el-icon-loading"
                @selection-change="handleTableRowsSelect"
                @current-change="handleTableCurrentRowChange"
              >
                <el-table-column type="selection" width="55" align="center">
                </el-table-column>
                <el-table-column
                  fixed="left"
                  label="操作"
                  width="100%"
                  align="center"
                >
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="primary"
                      icon="el-icon-edit-outline"
                      @click="$refs.editForm.openEditForm(true, scope.row)"
                      >变更
                    </el-button>
                  </template>
                </el-table-column>
                <el-table-column
                  type="index"
                  label="序号"
                  width="80"
                  align="center"
                ></el-table-column>
                <el-table-column
                  prop="houseStatus"
                  label="房源状态"
                  align="center"
                  width="150"
                >
                  <template slot-scope="scope">
                    <template
                      v-for="(item, index) in $store.state.DICT
                        .houseStatusSelect"
                    >
                      <el-tag
                        v-if="item.code === scope.row.houseStatus"
                        :key="index"
                        :type="item.theme"
                      >
                        {{ item.name }}
                      </el-tag>
                    </template>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="houseTitle"
                  label="房间标题"
                  align="center"
                  width="150"
                ></el-table-column>
                <el-table-column
                  prop="regionId"
                  label="地区"
                  align="center"
                  width="250"
                >
                  <template slot-scope="scope">
                    <el-cascader
                      v-model="scope.row.regionId"
                      :options="$store.state.DICT.regionCode"
                      :props="{
                        expandTrigger: 'hover',
                        checkStrictly: true,
                        emitPath: false,
                        value: 'id',
                        label: 'name',
                      }"
                      disabled
                    >
                    </el-cascader>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="detailLocation"
                  label="具体位置"
                  align="center"
                  width="300"
                ></el-table-column>
                <el-table-column
                  prop="houseType"
                  label="房源类型"
                  align="center"
                  width="150"
                >
                  <template slot-scope="scope">
                    <template
                      v-for="(item, index) in $store.state.DICT.houseTypeSelect"
                    >
                      <el-tag
                        v-if="item.code === scope.row.houseType"
                        :key="index"
                        :type="item.theme"
                      >
                        {{ item.name }}
                      </el-tag>
                    </template>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="provide"
                  label="配套服务设施"
                  align="center"
                  width="150"
                ></el-table-column>
                <el-table-column
                  prop="cost"
                  label="单价/天"
                  align="center"
                  width="120"
                ></el-table-column>
                <el-table-column
                  prop="discount"
                  label="折扣"
                  align="center"
                  width="120"
                ></el-table-column>
                <el-table-column label="库存" align="center" width="120">
                  <template slot-scope="scope">
                    <el-tag
                      v-if="scope.row.inventory - scope.row.ordering > 0"
                      type="success"
                    >
                      {{ scope.row.inventory - scope.row.ordering }}
                    </el-tag>
                    <el-tag v-else type="danger">
                      {{ scope.row.inventory - scope.row.ordering }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="ordering"
                  label="已预定"
                  align="center"
                  width="120"
                ></el-table-column>
                <el-table-column
                  prop="inventory"
                  label="房源数量"
                  align="center"
                  width="120"
                ></el-table-column>
                <el-table-column
                  prop="command"
                  label="入住要求"
                  align="center"
                  width="300"
                ></el-table-column>
                <el-table-column
                  prop="organizationId"
                  label="组织机构"
                  align="center"
                  width="120"
                ></el-table-column>
                <el-table-column
                  prop="createUser"
                  label="创建人"
                  align="center"
                  width="120"
                ></el-table-column>
                <el-table-column
                  prop="createUserName"
                  label="创建人姓名"
                  align="center"
                  width="150"
                ></el-table-column>
                <el-table-column
                  prop="createTime"
                  label="创建时间"
                  align="center"
                  width="180"
                ></el-table-column>
                <el-table-column
                  prop="updateUser"
                  label="更新人"
                  align="center"
                  width="120"
                ></el-table-column>
                <el-table-column
                  prop="updateUserName"
                  label="更新人姓名"
                  align="center"
                  width="150"
                ></el-table-column>
                <el-table-column
                  prop="updateTime"
                  label="更新时间"
                  align="center"
                  width="180"
                ></el-table-column>
              </el-table>
            </el-col>
            <!-- 分页组件 -->
            <el-col>
              <el-pagination
                background
                @size-change="handlePageSizeChange"
                @current-change="handleCurrentPageChange"
                :current-page="page.currentPage"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="page.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="page.total"
                align="center"
              >
              </el-pagination>
            </el-col>
            <!-- 详情管理区 -->
            <el-col>
              <el-divider content-position="center">
                <h3>房间详情管理区</h3>
              </el-divider>
              <el-tabs type="card">
                <el-tab-pane label="房间详情">
                  <Detail v-if="selectItem" :obj="selectItem"></Detail>
                </el-tab-pane>
                <el-tab-pane label="展示图配置">
                  <!-- 房源图片 -->
                  <HouseImage
                    ref="houseImage"
                    v-if="selectItem"
                    :houseItem="selectItem"
                  ></HouseImage>
                </el-tab-pane>
              </el-tabs>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加房源表单 -->
    <AddForm ref="addForm" @afterSubmit="afterSubmitHandle()"></AddForm>
    <!-- 编辑房源表单 -->
    <EditForm ref="editForm" @afterSubmit="afterSubmitHandle()"></EditForm>
    <!-- 审批房源表单 -->
    <Audit ref="audit" @afterSubmit="afterSubmitHandle()"></Audit>
  </div>
</template>

<script>
import AddForm from "./addForm";
import EditForm from "./editForm";
import Detail from "./detail";
import Audit from "./audit";
import HouseImage from "@/views/HouseImage";
import {
  DateTimeRange_Picker_Option,
  DateRange_Picker_Option,
  Date_Picker_Option,
} from "@/utils/datePicker";

export default {
  name: "houseManage",
  components: {
    AddForm,
    EditForm,
    HouseImage,
    Detail,
    Audit,
  },

  data() {
    return {
      // 分页参数
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      // 【房源】数据表
      tableData: [],
      // 【房源】表已选 IDs
      tableCheckIds: [],
      tableCheckRows: [],
      // 数据加载
      requestLoading: false,
      // 查询表单参数
      queryForm: {
        id: null,
        houseTitle: null,
        regionId: null,
        detailLocation: null,
        houseType: null,
        provide: null,
        detail: null,
        cost: null,
        discount: null,
        command: null,
        houseStatus: null,
        organizationId: null,
        createUser: null,
        createUserName: null,
        createTime: null,
        updateUser: null,
        updateUserName: null,
        updateTime: null,
      },
      selectItem: null,
      // 日期选择快捷方式
      DateTimeRange_Picker_Option,
      DateRange_Picker_Option,
      Date_Picker_Option,
    };
  },

  // 组件创建时
  created() {
    // 页面元素初始化
  },

  // 组件挂载时
  mounted() {
    this.queryDataBtn();
  },

  methods: {
    // 表单提交后置处理
    afterSubmitHandle() {
      this.queryHouseApi();
      this.tableCheckIds = [];
      this.tableCheckRows = [];
    },

    // 处理表格行多选
    handleTableRowsSelect(val) {
      let ids = [];
      val.forEach((obj) => ids.push(obj.id));
      this.tableCheckIds = ids;
      this.tableCheckRows = val;
    },

    // 处理表格行单选
    handleTableCurrentRowChange(row, oldRow) {
      this.selectItem = row;
    },

    // ---------------- 分页参数处理 START-----------------
    handleCurrentPageChange(val) {
      this.page.currentPage = val;
      // 查询【房源】表
      this.queryHouseApi();
    },
    handlePageSizeChange(val) {
      this.page.pageSize = val;
      this.page.currentPage = 1;
      // 查询【房源】表
      this.queryHouseApi();
    },
    // ---------------- 分页参数处理 END-----------------

    // 查询【房源】
    queryDataBtn() {
      this.page.currentPage = 1;
      this.queryHouseApi();
    },

    // 删除数据后：最后一页逻辑处理、表格更新
    afterDelete(deleteCount) {
      // 最后一页（旧）
      let oldLastPage = Math.ceil(this.page.total / this.page.pageSize);
      // 最后一页（新）
      let currLastPage = Math.ceil(
        (this.page.total - deleteCount) / this.page.pageSize
      );
      // 如果删除最后一页，则将当前页更新为最新的最后一页
      if (this.page.currentPage == oldLastPage) {
        this.page.currentPage = currLastPage == 0 ? 1 : currLastPage;
      }
      // 更新表格
      this.queryHouseApi();
    },

    // 查询参数处理
    queryParamProcess() {
      let param = Object.assign({}, this.queryForm);
      param["pageNum"] = this.page.currentPage;
      param["pageSize"] = this.page.pageSize;

      if (this.queryForm.createTime) {
        param["createTimeStart"] = this.queryForm.createTime[0];
        param["createTimeEnd"] = this.queryForm.createTime[1];
      }
      if (this.queryForm.updateTime) {
        param["updateTimeStart"] = this.queryForm.updateTime[0];
        param["updateTimeEnd"] = this.queryForm.updateTime[1];
      }

      delete param.createTime;
      delete param.updateTime;

      return param;
    },

    // 查询【房源】API
    queryHouseApi() {
      this.requestLoading = true;

      this.$api
        .queryHouse(this.queryParamProcess())
        .then((res) => {
          this.tableData = [];
          this.page.total = 0;

          let { status, message, data } = res.data;
          if (status == 200) {
            this.tableData = data.items;
            this.page.total = data.totalNum;
          } else if (status == 403) {
            this.$message({
              message: `权限不足！${message}`,
              type: "error",
              center: true,
              duration: 1680,
            });
          } else {
            this.$alert(`暂无数据记录！${message}`, "【房源】信息表", {
              type: "info",
              confirmButtonText: "确定",
              callback: (action) => {},
            });
          }

          this.requestLoading = false;
        })
        .catch((err) => {
          this.requestLoading = false;
          console.log(`【房源】查询接口发生错误: ${err}`);
        });
    },

    // 删除【房源】API
    batchDelHouseApi() {
      if (this.tableCheckIds.length == 0) {
        this.$alert("请在左侧列选中要删除的数据行！", "提示", {
          confirmButtonText: "确定",
          type: "warning",
          callback: (action) => {},
        });
        return;
      }

      this.$confirm("此操作将永久删除已选中的数据, 是否继续?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
      })
        .then(() => {
          const loading = this.$loading({
            target: document.querySelector(".data-table"),
            lock: true,
            text: "正在删除，请耐心等待！",
          });

          // 发起删除请求
          this.$api
            .batchDelHouse({ ids: this.tableCheckIds })
            .then((res) => {
              loading.close();

              let { status, message, data } = res.data; // 响应数据
              if (status == 200) {
                // 更新【房源】表
                this.afterDelete(data);
                // 提示信息
                this.$message({
                  type: "success",
                  message: `删除成功！删除记录数：${data}`,
                  duration: 1680,
                });
              } else if (status == 403) {
                this.$message({
                  message: `权限不足！${message}`,
                  type: "error",
                  center: true,
                  duration: 1680,
                });
                // this.$router.push("/login");
              } else {
                this.$message({
                  type: "warning",
                  message: `数据没有发生更改！${message}`,
                  duration: 1680,
                });
              }
            })
            .catch((err) => {
              loading.close();
              // 查询【房源】表
              this.queryHouseApi();
              console.log(`【房源】删除接口发生错误: ${err}`);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除。",
          });
        });
    },

    // 审批
    authSysRoleDatascope() {
      if (this.tableCheckIds.length == 0) {
        this.$alert("请在左侧列选中要操作的数据行！", "提示", {
          confirmButtonText: "确定",
          type: "warning",
          callback: (action) => {},
        });
        return;
      }

      this.$refs.audit.openEditForm(true, this.tableCheckRows);
    },
  },
};
</script>

<style lang="scss" scoped>
// 表单布局样式
@import "@/assets/css/form-layout.scss";
</style>
